# -*- coding: utf-8 -*-
"""
Created on Wed Aug 22 13:34:57 2018

@author: Who

比特家
http://www.bitjia.com/


"""

import requests
from bs4 import BeautifulSoup
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_kx(url):
    dates = []
    text = get_html_text(url)
    if not text:
        return None
    text = eval(get_html_text(url))
    for date in text:
        dates.append(date['date'])
    return dates


def get_dates_zx(url):
    dates = []
    text = get_html_text(url)
    if not text:
        return None
    soup = BeautifulSoup(text, 'lxml')
    data = soup.select('.index-news-date')
    dates = [date.get_text()[:10] for date in data]
    return dates


def count_process_one():  # 快讯
    d1 = 0
    d2 = 0
    d3 = 0
    url = 'http://www.bitjia.com/api/index.php/v1/quicknews'
    dates = get_dates_kx(url)
    if not dates:
        return (d1, d2, d3)
    print('----比特家快讯获取中----')
    for date in dates:
        s = day(date)
        if s == 0:
            d1 += 1
        elif s == 1:
            d2 += 1
        elif s == 2:
            d3 += 1
    return (d1, d2, d3)


def count_process_two():  # 资讯
    d1 = 0
    d2 = 0
    d3 = 0
    url = 'http://www.bitjia.com/'
    dates = get_dates_zx(url)
    if not dates:
        return (d1, d2, d3)
    print('----比特家资讯获取中----')
    for date in dates:
        s = day(date)
        if s == 0:
            d1 += 1
        elif s == 1:
            d2 += 1
        elif s == 2:
            d3 += 1
    return (d1, d2, d3)


def main():
    u = '比特家'
    t1 = count_process_one()
    t2 = count_process_two()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
